package com.openfarmanager.android;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import com.dropbox.client2.exception.DropboxException;
import com.openfarmanager.android.controllers.FileSystemController;
import com.openfarmanager.android.controllers.FileSystemControllerSmartphone;
import com.openfarmanager.android.core.network.dropbox.DropboxAPI;
import com.openfarmanager.android.model.NetworkEnum;
import com.openfarmanager.android.utils.Extensions;

public class Main extends FragmentActivity {

    public static int RESULT_CODE_PANELS_MODE_CHANGED = 100;

    private FileSystemController mFileSystemController;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_CODE_PANELS_MODE_CHANGED == resultCode) {
            Intent intent = getIntent();
            overridePendingTransition(0, 0);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            finish();

            overridePendingTransition(0, 0);
            startActivity(intent);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(App.sInstance.getSettings().isMultiPanelMode() ? R.layout.main_two_panels : R.layout.main_one_panel);
        if (findViewById(R.id.view_pager) == null) {
            mFileSystemController = new FileSystemController(getSupportFragmentManager());
        } else {
            mFileSystemController = new FileSystemControllerSmartphone(getSupportFragmentManager(), findViewById(R.id.root_view));
            if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("main_swipe_hint", false)) {
                showSwipeHint();
            }        
        }
        App.sInstance.setFileSystemController(mFileSystemController);

        mFileSystemController.restorePanelState();
    }

    private void showSwipeHint() {
        View view = getLayoutInflater().inflate(R.layout.main_swipe_hint, null);
        final PopupWindow popupWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT, true);

        view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PreferenceManager.getDefaultSharedPreferences(Main.this).edit().putBoolean("main_swipe_hint", true).commit();
                popupWindow.dismiss();
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try{
                    popupWindow.showAtLocation(findViewById(R.id.root_view), Gravity.CENTER, 0, 0);
                } catch (Exception ignored){

                }
            }
        }, 500);

    }
    
    @Override
    protected void onResume() {
        super.onResume();

        final DropboxAPI dropboxAPI = App.sInstance.getDropboxApi();

        if (dropboxAPI == null) {
            return;
        }

        if (dropboxAPI.getSession().authenticationSuccessful() && mFileSystemController.isNetworkAuthRequested()) {
            dropboxAPI.getSession().finishAuthentication();
            mFileSystemController.resetNetworkAuth();

            Extensions.runAsynk(new Runnable() {
                @Override
                public void run() {
                    try {
                        com.dropbox.client2.DropboxAPI.Account account = dropboxAPI.accountInfo();
                        String userName = account.displayName + "(" + account.uid + ")";
                        dropboxAPI.storeAccessTokens(userName, dropboxAPI.getSession().getAccessTokenPair());
                        mFileSystemController.openNetworkPanel(NetworkEnum.Dropbox);
                    } catch (DropboxException e) {
                        e.printStackTrace();
                    }
                }
            });

        }
    }

    @Override
    protected void onPause() {
        try {
            super.onStop();
            mFileSystemController.savePanelState();
        } catch (IllegalStateException ignore) {
            //something very unexpected, but there is a lot of crashes...
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(mFileSystemController.onKeyDown(keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }
}
